package com.anxinr.service.impl;

import com.anxinr.constant.ShopConstant;
import com.anxinr.mapper.AddressMapper;
import com.anxinr.pojo.dto.AddressDTO;
import com.anxinr.pojo.entity.Address;
import com.anxinr.service.AddressService;
import com.anxinr.util.UserInfoContext;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author anxinr
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService {
    @Autowired
    private AddressMapper addressMapper ;
    @Autowired
    private UserInfoContext userInfoContext ;

    /**
     * 保存收货地址
     * @param addr
     */
    @Override
    public void saveAddr(AddressDTO addr) {
        Address address = new Address();
        /**设置当前登录用户信息*/
        addr.setUserId(userInfoContext.getUser().getId());
        BeanUtils.copyProperties(addr,address);
        this.save(address) ;

//        addressMapper.saveAddress(addr) ;
    }

    /**
     * 设置默认收货地址
     * @param id
     */
    @Override
    public void defaultAddr(Long id) {
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<>();
        /**修改所有当前用户收货地址为不默认*/
        wrapper.eq(Address::getUserId,userInfoContext.getUser().getId()) ;
        wrapper.set(Address::getIsDefault,ShopConstant.ADDR_DEFAULT_FALSE);
        this.update(wrapper) ;
        wrapper.clear();
        /**置当前地址为默认地址*/
        wrapper.eq(Address::getId,id) ;
        wrapper.set(Address::getIsDefault,ShopConstant.ADDR_DEFAULT_TRUE) ;
        this.update(wrapper) ;
    }

    @Override
    public List<Address> queryAddress() {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId,userInfoContext.getUser().getId()) ;
        wrapper.orderByAsc(Address::getIsDefault) ;
        return this.list(wrapper);
    }
}
